<?php

/**
 * Webman gRPC扩展包示例
 * 
 * 本示例展示了如何使用Webman gRPC扩展包的各种功能，包括：
 * 1. 基本的gRPC服务端和客户端
 * 2. 连接池管理
 * 3. 序列化优化
 * 4. 内存管理
 * 5. 模块化设计
 * 6. 事件驱动架构
 * 7. 性能监控
 */

require_once __DIR__ . '/vendor/autoload.php';

use WebmanGrpc\GrpcManager;
use WebmanGrpc\Client\GrpcClient;
use WebmanGrpc\Event\EventBus;
use WebmanGrpc\Event\Event;
use WebmanGrpc\Event\EventListenerInterface;
use WebmanGrpc\Module\BaseModule;
use WebmanGrpc\Module\ModuleManager;

// 创建自定义事件监听器
class CustomEventListener implements EventListenerInterface
{
    public function handle($event): void
    {
        echo "事件: {$event->getName()}, 数据: " . json_encode($event->getData()) . "\n";
    }
    
    public function getPriority(): int
    {
        return 100;
    }
}

// 创建自定义模块
class CustomModule extends BaseModule
{
    public function getName(): string
    {
        return 'custom_module';
    }
    
    public function getVersion(): string
    {
        return '1.0.0';
    }
    
    public function getDependencies(): array
    {
        return [];
    }
    
    public function initialize(): bool
    {
        echo "自定义模块初始化\n";
        return true;
    }
    
    public function start(): bool
    {
        echo "自定义模块启动\n";
        return true;
    }
    
    public function stop(): bool
    {
        echo "自定义模块停止\n";
        return true;
    }
}

// 示例1: 基本使用
echo "=== 示例1: 基本使用 ===\n";

// 获取gRPC管理器实例
$manager = GrpcManager::getInstance();

// 初始化gRPC扩展包
$config = [
    'connection_pool' => [
        'max_connections' => 10,
        'max_lifetime' => 300,
        'health_check_interval' => 30,
        'health_check_timeout' => 5,
    ],
    'serialization' => [
        'lite_mode' => false,
        'pool_enabled' => true,
        'cache_enabled' => true,
        'pool_config' => [
            'max_size' => 100,
            'min_size' => 5,
        ],
        'cache_size' => 1000,
    ],
    'memory' => [
        'memory_limit' => 100 * 1024 * 1024, // 100MB
        'warning_threshold' => 80 * 1024 * 1024, // 80MB
        'max_history_size' => 100,
        'monitoring_enabled' => true,
        'monitoring_interval' => 5,
    ],
];

$manager->initialize($config);

echo "gRPC扩展包初始化完成\n";

// 示例2: 连接池管理
echo "\n=== 示例2: 连接池管理 ===\n";

// 预热连接
$addresses = ['127.0.0.1:50051'];
$options = [
    'credentials' => \Grpc\ChannelCredentials::createInsecure(),
];

try {
    $manager->warmUpConnections($addresses, $options);
    echo "连接预热完成\n";
} catch (\Exception $e) {
    echo "连接预热失败: " . $e->getMessage() . "\n";
}

// 获取连接池统计
$poolStats = $manager->getConnectionPool()->getStats();
echo "连接池统计: " . json_encode($poolStats, JSON_PRETTY_PRINT) . "\n";

// 示例3: 序列化优化
echo "\n=== 示例3: 序列化优化 ===\n";

// 预热序列化
$messageClasses = [
    'stdClass',
];

$manager->warmUpSerialization($messageClasses);
echo "序列化预热完成\n";

// 获取序列化统计
$serializationStats = $manager->getStats()['serialization'];
echo "序列化统计: " . json_encode($serializationStats, JSON_PRETTY_PRINT) . "\n";

// 示例4: 内存管理
echo "\n=== 示例4: 内存管理 ===\n";

// 获取内存使用情况
$memoryUsage = $manager->getStats()['memory'];
echo "内存使用情况: " . json_encode($memoryUsage, JSON_PRETTY_PRINT) . "\n";

// 检查内存限制
$memoryCheck = \WebmanGrpc\Memory\MemoryManager::checkMemoryLimit();
echo "内存限制检查: " . json_encode($memoryCheck, JSON_PRETTY_PRINT) . "\n";

// 示例5: 模块化设计
echo "\n=== 示例5: 模块化设计 ===\n";

// 获取模块管理器
$moduleManager = $manager->getModuleManager();

// 注册自定义模块
$customModule = new CustomModule();
$moduleManager->register($customModule);
echo "自定义模块注册完成\n";

// 获取所有模块状态
$moduleStatus = $moduleManager->getAllModuleStatus();
echo "模块状态: " . json_encode($moduleStatus, JSON_PRETTY_PRINT) . "\n";

// 示例6: 事件驱动架构
echo "\n=== 示例6: 事件驱动架构 ===\n";

// 获取事件总线
$eventBus = $manager->getEventBus();

// 添加事件监听器
$eventListener = new CustomEventListener();
$eventBus->addListener('custom_event', $eventListener);
echo "事件监听器添加完成\n";

// 发布事件
$event = new Event('custom_event', ['key' => 'value']);
$eventBus->publish($event);

// 获取事件统计
$eventStats = $eventBus->getStats();
echo "事件统计: " . json_encode($eventStats, JSON_PRETTY_PRINT) . "\n";

// 示例7: 性能监控
echo "\n=== 示例7: 性能监控 ===\n";

// 启用性能监控
$manager->enablePerformanceMonitoring();

// 模拟一些请求
$monitor = $manager->getPerformanceMonitor();
for ($i = 0; $i < 5; $i++) {
    $requestId = $monitor->startRequest("method_$i", "service_$i", ['request_id' => $i]);
    usleep(10000); // 模拟处理时间
    $monitor->endRequest($requestId, 200, 1024, 2048);
}

// 获取性能数据
$performanceData = $monitor->getPerformanceData();
echo "性能数据: " . json_encode($performanceData, JSON_PRETTY_PRINT) . "\n";

// 生成性能报告
$report = $monitor->generateReport();
echo "\n性能报告:\n";
echo $report . "\n";

// 示例8: 综合统计
echo "\n=== 示例8: 综合统计 ===\n";

// 获取所有统计信息
$allStats = $manager->getStats();
echo "综合统计: " . json_encode($allStats, JSON_PRETTY_PRINT) . "\n";

// 示例9: 环境检查
echo "\n=== 示例9: 环境检查 ===\n";

// 检查环境
$envCheck = $manager->checkEnvironment();
echo "环境检查: " . json_encode($envCheck, JSON_PRETTY_PRINT) . "\n";

// 示例10: 版本信息
echo "\n=== 示例10: 版本信息 ===\n";

// 获取版本信息
$versionInfo = $manager->getVersionInfo();
echo "版本信息: " . json_encode($versionInfo, JSON_PRETTY_PRINT) . "\n";

// 清理资源
echo "\n=== 清理资源 ===\n";
$manager->cleanup();
echo "资源清理完成\n";

echo "\n示例执行完毕\n";